
import { DICT_TYPE, getIntDictOptions } from "@/utils/dict";
import { Col, Form, Input, Modal, Row, Select, InputNumber, Flex, Radio, Spin, TreeSelect, message } from "antd";
import React, { useState, useEffect, useRef, useImperativeHandle, useContext, } from "react";
import { menuApi } from "@/api";
import { Context, globalModal } from "@/data";
import { XxIconBed } from "@/ui";

const MenuForm = ({ onRef, getList = Function }) => {
    const { modal } = useContext(Context);
    const [formType, setFormType] = useState("add");
    const [treeData, setTreeData] = useState([]);
    const [show, setShow] = useState(false);
    const [loading, setLoading] = useState(false);
    const [form] = Form.useForm();
    const menuType = Form.useWatch('menuType', form);

    /**@description 加载菜单树 */
    const loadMenuTree = async () => {
        const { data, code, msg } = await menuApi.getMenuList();
        setTreeData(data?.treeData)
    }


    /**@description 表单布局 */
    const formItemLayout = {
        labelCol: {
            xs: {
                span: 24,
            },
            sm: {
                span: 6,
            },
        },
        wrapperCol: {
            xs: {
                span: 24,
            },
            sm: {
                span: 20,
            },
        },
    };

    /**@description 取消 */
    const onCanle = () => {
        setShow(false);
    }

    /**@description 添加|修改操作 */
    // const open = async (type = String || undefined, id, parentId) => {
    const open = async ({
        type = String || undefined,
        record = {},
        // id,
        // parentId
    }) => {
        setFormType(type)
        const { id = undefined, parentId = undefined } = record;
        setShow(true);
        loadMenuTree();
        form.resetFields();
        form.setFieldValue("type", "action." + type)




        if (type === "update") {
            form.setFieldValue("parentId", parentId);

            if (id) {
                try {
                    setLoading(true);
                    const { data, msg, code } = await menuApi.getMenu(id);
                    if (code === 0) {
                        form.setFieldsValue({
                            type: type || undefined,
                            ...data
                        });
                    } else {
                        modal.error({
                            centered: true,
                            title: "提示",
                            content: msg
                        })
                    }



                } catch (error) {

                } finally {
                    setLoading(false);
                }
            }
        } else if (type === "add") {
            // // 新增 
            form.setFieldsValue({
                "parentId": id,
                menuType: "1"
            })
        } else {
            form.setFieldValue("parentId", "0");
        }


    }

    /**@description 异步保存数据 */
    const createMenu = async (value) => {
        try {
            const data = await menuApi.createMenu(value);
            getList();
            onCanle();
        } catch (error) {

        } finally {

        }

    }

    /**@description 校验表单 */
    const validateForm = async () => {
        form.validateFields().then(res => {
            createMenu(res)
        })
    }

    /**@description 向外暴露方法 */
    useImperativeHandle(onRef, () => ({
        open
    }))

    /**@description form表单props配置 */
    const formProps = {
        form,
        rules: {
            parentId: [{ required: true, message: '上级菜单为必选项' }],
            menuName: [{ required: true, message: '菜单名称不能为空' }],
            menuType: [{ required: true, message: '菜单类型为必选项' }],
            permissionMark: [{ required: true, message: '权限标识不能为空' }],
            status: [{ required: true, message: '状态选项为必选项' }],
        },
        initData: {
            type: undefined,
            parentId: "0",
            menuType: "1"
        }
    }

    useEffect(() => {
        show && loadMenuTree();
        !show && form.resetFields()
    }, [show])


    const getPermissionInputPlaceholderText = {
        "1": "示例：user",
        "2": "示例：user:list",
        "3": "示例：user:list:add",
        "4": "示例：menu:link:baidu"
    }

    return (
        <>
            <Modal
                title="菜单编辑"
                width={1000}
                open={show}
                centered={true}
                destroyOnClose={true}
                onCancel={onCanle}
                onOk={validateForm}
            >
                <Spin spinning={loading}>
                    <Form
                        {...formItemLayout}
                        {...formProps}
                    >
                        <Row gutter={24}>
                            <Col span={12} style={{ display: "none" }} >
                                <Form.Item label="id" name="id">
                                    <Input />
                                </Form.Item>
                            </Col>
                            <Col span={12}>
                                <Form.Item rules={formProps.rules["parentId"]} label="上级菜单" name="parentId">
                                    <TreeSelect
                                        treeData={treeData}
                                        fieldNames={{
                                            label: "menuName",
                                            value: "id"
                                        }}
                                    />

                                </Form.Item>
                            </Col>
                            <Col span={12}>
                                <Form.Item rules={formProps.rules["menuName"]} label="菜单名称" name="menuName">
                                    <Input placeholder="请输入菜单名称" />
                                </Form.Item>
                            </Col>
                            <Col span={12}>
                                <Form.Item rules={formProps.rules["menuType"]} label="菜单类型" name="menuType">
                                    <Radio.Group
                                        disabled={formType === "add" ? false : true}
                                        block
                                        options={getIntDictOptions(DICT_TYPE.SYSTEM_MENU_TYPE)}
                                        defaultValue={"1"}
                                        optionType="button"
                                        buttonStyle="solid"
                                    />
                                </Form.Item>
                            </Col>
                            <Col span={12}>
                                <Form.Item label="菜单图标" name="menuIcon">
                                    <XxIconBed />
                                </Form.Item>
                            </Col>
                            {
                                menuType === "3" ? null :
                                    <Col span={12}>
                                        <Form.Item label={menuType === "4" ? "链接地址" : "路由地址"} tooltip="访问的路由地址，如：`/user/list`。如需外网地址（菜单类型为链接）时，则以 `http(s)://` 开头" name="routerPath">
                                            <Input placeholder={menuType === "4" ? "示例：https://xxx.com" : menuType === "1" ? "示例：/user" : "示例：/user/list"} />
                                        </Form.Item>
                                    </Col>
                            }

                            <Col span={12}>
                                <Form.Item label="显示排序" name="sort">
                                    <InputNumber defaultValue={1} />
                                </Form.Item>
                            </Col>
                            {
                                menuType === "2" &&
                                <>
                                    <Col span={12}>
                                        <Form.Item tooltip="" label="组件名称" name="componentName">
                                            <Input />
                                        </Form.Item>
                                    </Col>
                                    <Col span={12}>
                                        <Form.Item label="组件地址" name="componentPath">
                                            <Input />
                                        </Form.Item>
                                    </Col>

                                </>
                            }
                            {
                                <Col span={12}>
                                    <Form.Item
                                        rules={formProps.rules["permissionMark"]}
                                        label="权限标识"
                                        name="permissionMark"
                                        tooltip="Controller 方法上的权限字符，如：@PreAuthorize(`@ss.hasPermission('system:user:list')`)"
                                    >
                                        <Input
                                            placeholder={getPermissionInputPlaceholderText[menuType]}
                                        />
                                    </Form.Item>
                                </Col>
                            }
                            <Col span={12}>
                                <Form.Item label="菜单状态" name="status">
                                    <Radio.Group
                                        defaultValue={"1"}
                                        options={getIntDictOptions(DICT_TYPE.COMMON_STATUS)}
                                        optionType="button"
                                        buttonStyle="solid"
                                    />
                                </Form.Item>
                            </Col>
                            <Col span={12}>
                                <Form.Item tooltip="配置菜单是否在左侧菜单显示" label="是否显示" name="visible">
                                    <Radio.Group
                                        defaultValue={"1"}
                                        options={getIntDictOptions(DICT_TYPE.SYSTEM_MENU_STATUS)}
                                        optionType="button"
                                        buttonStyle="solid"
                                    />
                                </Form.Item>
                            </Col>
                            <Col span={12}>
                                <Form.Item label="高亮归属" name="activeMenu" tooltip="当菜单为隐藏状态的时候，可配置高亮菜单，即当跳转到配置的高亮菜单的时候，系统左侧会高亮对应的菜单" >
                                    <Input />
                                </Form.Item>
                            </Col>
                            <Col span={12}>
                                <Form.Item tooltip="当此路由打开时，需要关闭的时候进行询问，一般适用于编辑页面，避免失误关闭导致未保存数据" label="关闭询问" name="askBeforeClose">
                                    <Radio.Group
                                        defaultValue={"0"}
                                        options={getIntDictOptions(DICT_TYPE.YES_OR_NO)}
                                        optionType="radio"
                                        buttonStyle="solid"
                                    />
                                </Form.Item>
                            </Col>
                        </Row>
                    </Form>
                </Spin>

            </Modal>
        </>
    )
}
export default MenuForm;